<template >
  <a-spin :spinning="confirmLoading"  >
    <JFormContainer :disabled="disabled" >
      <template #detail >
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="CInvoiceTaskForm">
          <a-row  >
			 <a-col :span="12">
			 	<a-form-item label="主项目" v-bind="validateInfos.projectId" id="CSubProjectForm-projectId" name="projectId">
			 		 <j-dict-select-tag showSearch="true"    v-model:value="formData.projectId"
					 @change="projectIdChange"
					 :disabled="isReadOnly"
					dictCode="c_project_application,project_name,id" placeholder="请输入主项目"  allow-clear />
			 	</a-form-item>
			</a-col>
						<a-col :span="12">
							<a-form-item label="开票金额" v-bind="validateInfos.invoiceAmount" id="CInvoiceTaskForm-invoiceAmount" name="invoiceAmount">
								<a-input-number v-model:value="formData.invoiceAmount" 
								:disabled="isReadOnly"
								placeholder="请输入开票金额" style="width: 100%" />
							</a-form-item>
						</a-col>
					<a-col :span="12">
						<a-form-item label="申请附件" v-bind="validateInfos.attachmentUrl" id="CProjectApplicationForm-attachmentUrl" name="attachmentUrl">
							<j-upload v-model:value="formData.attachmentUrl" dragger="true"  :disabled="isReadOnly"  :show-upload-list="{ showDownloadIcon: true, showRemoveIcon: true }"  ></j-upload>
						</a-form-item>
					</a-col>
					<Description size="middle" title="供应商信息" :bordered="false" :column="2" :data="personData" :schema="personSchema" />
					<Description size="middle" title="供应商银行信息" :bordered="false" :column="2" :data="bankData" :schema="bankSchema" />
					

						<a-col :span="24" v-if="formData.status !==''">
						  <a-card title="审核">
							  <a-col :span="24">
								<a-form-item label="审核附件" v-bind="validateInfos.auditFile" id="CProjectApplicationForm-auditFile" name="auditFile">
									<j-upload v-model:value="formData.auditFile"  dragger="true"  :disabled="isAuditReadOnly"  :show-upload-list="{ showDownloadIcon: true, showRemoveIcon: true }"></j-upload>
								</a-form-item>
							  </a-col>
							  <a-col :span="24">
								<a-form-item label="审核描述" v-bind="validateInfos.auditResults" id="CProjectApplicationForm-auditResults" name="auditResults">
									<a-textarea v-model:value="formData.auditResults" :disabled="isAuditReadOnly" :rows="4" placeholder="请审核描述" />
								</a-form-item>
							  </a-col>
							  <div v-if="formData.status==='待审核'  && sysUser.roleCode.includes('财务')">
								<div class="my-2" style="text-align: center;">
								  <a-button type="primary" @click="caiwuClikc(true)" preIcon="mdi:page-next-outline" > 同意 </a-button>
								  <a-button type="primary" @click="caiwuClikc(false)" class="ml-2" danger preIcon="mdi:page-next-outline" >拒绝</a-button>
								</div>
							</div>
							</a-card>
						</a-col>	
					
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import { defHttp } from '/@/utils/http/axios';
  import { Description } from '/@/components/Description/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
  import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
  import { getValueType } from '/@/utils';
  import { DescItem } from '/@/components/Description/index';
  import { saveOrUpdate ,getSubProjectList,getSubTaskList,getContractorInfo,postAudit} from '../CInvoiceTask.api';
  import {getLoginUser} from '../../common.api.ts'
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({})},
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    projectId: '',   
    invoiceAmount: undefined,
    attachmentUrl: '',   
    status: '',   
    fileRecordId: '', 
	auditResults: '', 
	auditFile:'',
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  

  const isReadOnly = ref(false);
  const isAuditReadOnly = ref(true);
  const sysUser = ref({ roleCode: '' });
  
  const bankData=ref({});
  const bankSchema: DescItem[] = [
	 {
	     field: 'a1',
	    label: '发票公司名称',
	},
	{
	    field: 'a2',
	    label: '税务代码',
	},
	 {
	   field: 'a7',
	   label: '开户行',
	 },
	    {
	      field: 'a3',
	      label: '银行账号',
	    },
	    {
	      field: 'a4',
	      label: '电话',
	    },
	    {
	      field: 'a5',
	      label: '电子邮箱',
	    },
	    {
	      field: 'a6',
	      label: '地址',
	    },
   ];
  
 const personData = ref({});
 const personSchema: DescItem[] = [
		{
		  field: 'b1',
		  label: '供应商名称',
		},
		{
		  field: 'b2',
		  label: '联系人',
		},
		{
		  field: 'b3',
		  label: '联系电话',
		},
		{
		  field: 'b4',
		  label: '地址',
		},
    
  ];
  
  //表单验证
  const validatorRules = reactive({
    projectId: [{ required: true, message: '请输入项目!'},],
	subProjectId: [{ required: true, message: '请输入子项目!'},],
    invoiceAmount: [{ required: true, message: '请输入开票金额!'},],
	subTaskId: [{ required: true, message: '请输入任务!'},],
	
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });

  
  /**
   * 新增
   */
  function add() {
    edit({});
  }

  /**
   * 编辑
   */
   async function edit(record) { // 将 edit 函数声明为 async
   	personData.value ={}
   	bankData.value ={}
   	isReadOnly.value = false
   	if(record.id){
   		isReadOnly.value = false
   	}
   	isAuditReadOnly.value = true
   	if(record.id && record.status==="待审核"){
   		isAuditReadOnly.value = false
   	}
   	
   	
       nextTick(() => {
         resetFields();
         const tmpData = {};
         Object.keys(formData).forEach((key) => {
           if(record.hasOwnProperty(key)){
             tmpData[key] = record[key]
           }
         })
   	  formData['subProjectId']=record.subProjectId
   	  formData['subTaskId']=record.subTaskId
         //赋值
         Object.assign(formData, tmpData);
       });
     }

  /**
   * 提交数据
   */
  async function submitForm() {
    try {
      // 触发表单验证
      await validate();
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

  

  
  

  
  async function projectIdChange(projectId){
	 
  }
 //  async function subTasChange(contractorInfoId){
	// if(contractorInfoId){
	// 	debugger
	// 	const selectedTask = subTaskList.value.find(task => task.value === contractorInfoId);
	// 	const entityInfo = selectedTask.entityInfo
	// 	const params = {'id':entityInfo.contractorId}
	// 	const response = await getContractorInfo(params);
	// 	if(response){
	// 			  personData.value = {
	// 			     b1: response.contactName,//供应商名称
	// 			     b2: response.contactPerson,//联系人
	// 			     b3: response.contactPhone,//联系电话
	// 			     b4: response.address,//地址
	// 			   };
				   
	// 			   bankData.value= {
	// 			     a1: response.taxName,
	// 			     a2: response.taxId,
	// 			     a3: response.taxBankAccount,
	// 			     a4: response.contactPhone,
	// 			   	a5: response.email,
	// 			   	a6: response.address,
	// 				a7: response.taxBank,
	// 			   };  
	// 	}
	// }
 //  }
  
  async function getUserData(){
  	  sysUser.value = await getLoginUser();
  }
  onMounted(() => {
	
     getUserData()
 });
  
  async function caiwuClikc(status){
	  if(status){//同意
		  if(formData.auditFile ===""){
			  alert('审核文件不能为空')
			  return
		  }
		  if(formData.auditResults==="" ){
		  	 alert('审核描述不能为空')
			 return
		  }
		  const params = {'auditFile':formData.auditFile,'auditResults':formData.auditResults,'id':formData.id,'status':'完成'}
		  const response = await  postAudit(params)
	  }else{//拒绝
		 if(formData.auditResults===""){
		 	 alert('审核描述不能为空')
			 return
		 }
		 const params = {'auditFile':formData.auditFile,'auditResults':formData.auditResults,'id':formData.id,'status':'拒绝'}
		 const response = await  postAudit(params)
	  }
	  window.location.reload(); // Refresh the page after audit
	  
  }
  

  defineExpose({
    add,
	caiwuClikc,
    edit,
    submitForm,
	projectIdChange,
	personData,
	personSchema,
	isReadOnly,
	sysUser
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
	height: 400px;
  }
</style>
